package com.sky.service.impl;

import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.dto.common.PageRequest;
import com.sky.dto.common.ParamsID;
import com.sky.dto.common.QueryParams;
import com.sky.entity.Department;
import com.sky.entity.Instructor;
import com.sky.exception.CommonException;
import com.sky.mapper.DepartmentMapper;
import com.sky.mapper.InstructorMapeer;
import com.sky.result.PageResult;
import com.sky.service.DepartmentService;
import com.sky.service.InstructorService;
import com.sky.vo.InstructorInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class InstructorServiceImpl implements InstructorService {
    @Autowired
    private InstructorMapeer instructorMapeer;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DepartmentMapper departmentMapper;
    /**
     * 分页查询 获取所有用户的信息
     * @param queryParams
     * @return
     */
    @Override
    public PageResult getAllInstructor(PageRequest<QueryParams> queryParams) {
        PageHelper.startPage(queryParams.getPageNum(), queryParams.getPageSize());
        departmentService.resolveDepartmentFilter(queryParams.getParams());
        List<Instructor> instructors = instructorMapeer.getAllInstructor(queryParams.getParams());
        PageInfo<Instructor> pageInfo = new PageInfo<>(instructors);
        List<InstructorInfoVO> results = pageInfo.getList().stream().map(instructor -> {
            InstructorInfoVO temp = new InstructorInfoVO();
            BeanUtils.copyProperties(instructor, temp);
            temp.setDepartment(departmentService.buildDepartmentPath(instructor.getDepartmentId()))
                    .setRoles(JSONUtil.toList(JSONUtil.parseArray(instructor.getRoles()), String.class))
                    .setPermissions(JSONUtil.toList(JSONUtil.parseArray(instructor.getPermissions()), String.class));
            return temp;
        }).collect(Collectors.toList());
        return new PageResult(pageInfo.getTotal(), results);
    }

    /**
     * 新增用户信息
     * @param instructorAddDTO
     */
    @Override
    @Transactional
    public void addInstructor(InstructorInfoVO instructorAddDTO) {
        // 还原设置
        Instructor instructor = new Instructor();
        BeanUtils.copyProperties(instructorAddDTO, instructor);
        // 设置初始密码为123456
        instructor.setRoles(JSONUtil.toJsonStr(instructorAddDTO.getRoles()))
            .setPermissions(JSONUtil.toJsonStr(instructorAddDTO.getPermissions()))
            .setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()))
    ;
        // 插入数据
        instructorMapeer.addInstructor(instructor);
        // 如果是部门管理员 -先判断当前部门是否有管理员了，在加入
        if(instructorAddDTO.getPermissionLevel() == 1){
            Department dept = departmentMapper.getDepartmentById(instructor.getDepartmentId());
           if(dept != null){
               if(dept.getInstructorId() != null && !dept.getInstructorId().isEmpty()) {
                   // 如果已经有管理员了，抛出异常
                   throw new CommonException("改部门下已有管理员，请勿重复添加！");
               }else{
                   dept.setInstructorId(instructor.getId())
                           .setDepartmentLeader(instructor.getName());
                   departmentMapper.updateDepartment(dept);
               }
           }else {
                throw new CommonException(MessageConstant.DEPT_NOFIND_ERR);
           }
        }
        String key = "instructor:time" + instructor.getId();
        // 获取当前系统时间
        long currentTimeMillis = System.currentTimeMillis();
        // 设置用户账号缓存 确保初始账号可以操作什么的
        redisTemplate.opsForValue().set(key, currentTimeMillis, 48, TimeUnit.HOURS);
        log.info("新增用户信息:{}", instructor);
    }

    /**
     * 修改用户信息
     * @param instructorInfoVO
     */
    @Override
    public void editInstructor(InstructorInfoVO instructorInfoVO) {
        // 还原设置
        Instructor instructor = new Instructor();
        BeanUtils.copyProperties(instructorInfoVO, instructor);
        String roles = JSONUtil.toJsonStr(instructorInfoVO.getRoles());
        String permissions = JSONUtil.toJsonStr(instructorInfoVO.getPermissions());
        instructor.setRoles(roles)
                .setPermissions(permissions);
        instructorMapeer.updateInstructor(instructor);
    }

    /**
     * 删除竞赛教师
     * @param paramsIDs
     */
    @Override
    public void deleteInstructor(ParamsID paramsIDs) {
        // 先统计paramsID总数，在计算实际可删除的数量
        int totalCount = paramsIDs.getIds().size();
        int deletedCount = 0;
        for (String id : paramsIDs.getIds()) {
            String key = "instructor:time" + id;
            if(redisTemplate.hasKey(key)) {
                // 删除用户
                instructorMapeer.deleteInstructorById(id);
                departmentMapper.deleteDepartmentLeader(id);
                deletedCount++;
                // 清理redis中用户未激活的标识
                redisTemplate.delete("instructor:time:" + id);
            }
        }
        if (deletedCount < totalCount) {
            // 如果有未删除的用户，抛出异常
            throw new CommonException("成功删除 " + deletedCount + " 个用户，本次操作共 " + totalCount + " 个用户。");
            }
        }

    /**
     * 获取一级部门的负责人信息
     * @param paramsID 一级部门id
     * @return
     */
    @Override
    public List<Instructor> getOnePeople(ParamsID paramsID,String type) {
        // 构造出部门id集合
//        List<String> departmentIds = new ArrayList<>();
//        for(String id : paramsID.getIds()) {
//            List<String> temp = departmentService.getDepartmentIdsById(id, 1);
//            departmentIds.addAll(temp);
//        }
//        List<String> distinctIds = new ArrayList<>(new HashSet<>(departmentIds)); // 去重处理
        if(type.equals("school")){
            List<Instructor> result = instructorMapeer.getOnePeople(paramsID);
            return result;
        }else if(type.equals("auto")){
            List<Instructor> result = instructorMapeer.getSchoolManager();
            return result;
        }
        else {
            List<Instructor> result = instructorMapeer.getTeamManage(paramsID);
            return result;
        }
    }
}
